import { fileURLToPath, URL } from 'node:url'

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/dist/vite'
import ReactivityTransform from '@vue-macros/reactivity-transform/dist/vite'
import Components from "unplugin-vue-components/dist/vite"
//import { ElementPlusResolver } from "unplugin-vue-components/dist/resolvers"
import compression from 'vite-plugin-compression'

function ElementPlusResolver() {
    return (name) => {
        if (name.startsWith('El') && name !== 'ElButton') {
            return {
                importName: name,
                path: 'element-plus',
            };
        }
    };
}

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [
        vue(),
        AutoImport({
            imports: ['vue', 'vue-router'],
        }),
        ReactivityTransform(),
        Components({
            deep: true,
            dirs: ["src/components"],
            resolvers: [ElementPlusResolver()]
        }),
        compression({
            verbose: true,
            disable: false,
            threshold: 10240,
            algorithm: 'gzip',
            ext: '.gz',
        }),
    ],
    resolve: {
        extensions: ['.mjs', '.js', '.ts', '.jsx', '.tsx', '.json', '.vue'],
        alias: {
            '@': fileURLToPath(new URL('./src', import.meta.url)),
            vue: 'vue/dist/vue.esm-bundler.js',
            '@usehook': fileURLToPath(new URL('./src/hooks', import.meta.url))
        },
        dedupe: ['vue'],
    },
    transpileDependencies: true,
    //关闭语法检查
    lintOnSave: false,
    //生产环境是否要生成 sourceMap
    productionSourceMap: false,
    assetsDir: "assets",
    base: '/',
    outputDir: "dist",
    server: {
        port: 9999,
        host: '0.0.0.0',
        https: false,
        open: false,
        hmr: true, // 开启热加载
    },
    publicDir: 'public',
    build: {
        outDir: "dist",
        assetsDir: "assets",
        sourcemap: false,
        minify: "terser",
        terserOptions: {
            compress: {
                drop_console: true,
                drop_debugger: true,
            },
        },
        rollupOptions: {
            output: {
                manualChunks(id) {
                    if (id.includes('node_modules')) {
                        return id.toString().split('node_modules/')[1].split('/')[0].toString()
                    }
                },
                entryFileNames: 'assets/[hash].js',//用于命名代码拆分时创建的共享块的输出命名
                chunkFileNames: 'assets/[hash].js',//用于输出静态资源的命名，[ext]表示文件扩展名
                assetFileNames: 'assets/[hash].[ext]',//用于输出静态资源的命名
            }
        }
    },
})
